import express from 'express';
import {
  sendVerificationCode,
  verifyCode,
  checkCodeStatus,
  cleanupExpiredCodes,
  getVerificationStats
} from '../controllers/emailVerificationController.js';
import { authenticateAdmin } from '../utils/jwt.js';
import { validateRequest } from '../utils/validation.js';
import Joi from 'joi';

const router = express.Router();

// 发送验证码验证规则
const sendCodeSchema = Joi.object({
  email: Joi.string()
    .email()
    .required()
    .messages({
      'string.email': '請輸入有效的郵箱地址',
      'any.required': '郵箱地址是必填項'
    }),

  type: Joi.string()
    .valid('register', 'reset_password')
    .default('register')
    .messages({
      'any.only': '驗證碼類型只能是register或reset_password'
    })
});

// 验证验证码验证规则
const verifyCodeSchema = Joi.object({
  email: Joi.string()
    .email()
    .required()
    .messages({
      'string.email': '請輸入有效的郵箱地址',
      'any.required': '郵箱地址是必填項'
    }),

  code: Joi.string()
    .pattern(/^\d{6}$/)
    .required()
    .messages({
      'string.pattern.base': '驗證碼必須是6位數字',
      'any.required': '驗證碼是必填項'
    }),

  type: Joi.string()
    .valid('register', 'reset_password')
    .default('register')
    .messages({
      'any.only': '驗證碼類型只能是register或reset_password'
    })
});

// 检查验证码状态验证规则
const checkStatusSchema = Joi.object({
  email: Joi.string()
    .email()
    .required()
    .messages({
      'string.email': '請輸入有效的郵箱地址',
      'any.required': '郵箱地址是必填項'
    }),

  type: Joi.string()
    .valid('register', 'reset_password')
    .default('register')
    .messages({
      'any.only': '驗證碼類型只能是register或reset_password'
    })
});

// 验证中间件
const sendCodeValidation = validateRequest(sendCodeSchema, 'body');
const verifyCodeValidation = validateRequest(verifyCodeSchema, 'body');
const checkStatusValidation = validateRequest(checkStatusSchema, 'query');

/**
 * @route POST /api/email-verification/send
 * @desc 发送邮箱验证码
 * @access Public
 */
router.post('/send', sendCodeValidation, sendVerificationCode);

/**
 * @route POST /api/email-verification/verify
 * @desc 验证邮箱验证码
 * @access Public
 */
router.post('/verify', verifyCodeValidation, verifyCode);

/**
 * @route GET /api/email-verification/status
 * @desc 检查验证码状态
 * @access Public
 */
router.get('/status', checkStatusValidation, checkCodeStatus);

/**
 * @route POST /api/email-verification/cleanup
 * @desc 清理过期验证码
 * @access Private (Admin)
 */
router.post('/cleanup', authenticateAdmin, cleanupExpiredCodes);

/**
 * @route GET /api/email-verification/stats
 * @desc 获取验证码统计信息
 * @access Private (Admin)
 */
router.get('/stats', authenticateAdmin, getVerificationStats);

export default router;
